<?php

use exceptions\BadRequestException;
use Yaf\Exception;
use Yaf\Exception\LoadFailed;

/**
 * 错误控制器
 * - 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 */
class ErrorController extends BaseController
{
    /**
     * 支持直接通过参数获取异常
     * @param Throwable $exception
     * @return bool
     */
    public function errorAction(Throwable $exception): bool
    {
        try {
            throw $exception;
        } catch (BadRequestException $ex) {
            // 业务异常
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        } catch (LoadFailed $ex) {
            // 加载失败
            http_response_code(404);
            $code = $ex->getCode();
            $msg = str_replace(BASE_PATH, '', $ex->getMessage());
        } catch (Error|Exception|Throwable $ex) {
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        }

        return $this->fail($msg, $code);
    }
}
